package com.powernode.util;

import com.powernode.constant.AuthConstants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.time.Duration;

/**
 * 令牌TOKEN管理器
 */
@Component
public class TokenManager {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Async
    public void flushTokenTime(String token,Boolean rememberMe) {
        // 获取当前令牌TOKEN的有效时长
        Long expireIn = stringRedisTemplate.getExpire(AuthConstants.TOKEN_REDIS_KEY_PREFIX + token);
        // 判断是否选中“记住我”
        if (rememberMe) {
            // 判断令牌TOKEN有效时长是否小于TOKEN阈值
            if (expireIn < AuthConstants.REMEMBER_ME_TOKEN_THRESHOLD) {
                // 小于：令牌TOKEN续约
                stringRedisTemplate.opsForValue().set(AuthConstants.TOKEN_REDIS_KEY_PREFIX+token,"", Duration.ofSeconds(AuthConstants.REMEMBER_ME_TOKEN_TIME));
            }
        } else {
            // 判断令牌TOKEN有效时长是否小于TOKEN阈值
            if (expireIn < AuthConstants.TOKEN_THRESHOLD) {
                // 小于：令牌TOKEN续约
                stringRedisTemplate.opsForValue().set(AuthConstants.TOKEN_REDIS_KEY_PREFIX+token,"", Duration.ofSeconds(AuthConstants.TOKEN_TIME));
            }
        }

    }

}
